package com.hepinghospital.user.ui.activity.prescription;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hepinghospital.user.R;
import com.hepinghospital.user.adapter.MedicineAdapter;
import com.hepinghospital.user.base.BaseActivity;
import com.hepinghospital.user.base.BaseApplication;
import com.hepinghospital.user.eventbus.AlipaySuccessEvent;
import com.hepinghospital.user.ui.activity.userinfo.MyAddressActivity;
import com.hepinghospital.user.ui.dialog.ALiPayDialog;
import com.hepinghospital.user.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.observer.BaseObserver;
import com.rest.response.AddressResponse;
import com.rest.response.MedicineListResponse;
import com.rest.response.PayResponse;
import com.rest.response.PrescriptionResponse;
import com.rest.response.SwitchResponse;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.UtilString;

/**
 * Description  处方支付
 * Created by lbj on 2021/8/25 13:53
 * @author DELL
 */

public class MedicineDetailActivity extends BaseActivity {

    @BindView(R.id.delivery_container)
    LinearLayout delivery_container;
    @BindView(R.id.express_container)
    ConstraintLayout express_container;
    @BindView(R.id.pay_container)
    ConstraintLayout pay_container;
    @BindView(R.id.tv_express_status)
    TextView tv_express_status;
    @BindView(R.id.tv_express_no)
    TextView tv_express_no;
    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.tv_addr)
    TextView tv_addr;
    @BindView(R.id.tv_phone)
    TextView tv_phone;
    @BindView(R.id.tv_patient_name)
    TextView tv_patient_name;
    @BindView(R.id.tv_patient_detail)
    TextView tv_patient_detail;
    @BindView(R.id.tv_patient_no)
    TextView tv_patient_no;
    @BindView(R.id.tv_diagnose)
    TextView tv_diagnose;
    @BindView(R.id.tv_advice)
    TextView tv_advice;
    @BindView(R.id.tv_notice)
    TextView tv_notice;
    @BindView(R.id.tv_hospital)
    TextView tv_hospital;
    @BindView(R.id.tv_doctor)
    TextView tv_doctor;
    @BindView(R.id.tv_medicine_doctor)
    TextView tvMedicineDoctor;
    @BindView(R.id.tv_time)
    TextView tv_time;
    @BindView(R.id.tv_phone_num)
    TextView tv_phone_num;
    @BindView(R.id.tv_price)
    TextView tv_price;
    @BindView(R.id.tv_price2)
    TextView tv_price2;
    @BindView(R.id.tv_remain_time)
    TextView tv_remain_time;
    @BindView(R.id.btn_express)
    RadioButton btn_express;
    @BindView(R.id.btn_store_self)
    RadioButton btn_store_self;
    @BindView(R.id.btn_hospital_self)
    RadioButton btn_hospital_self;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tv_detail_one)
    TextView tvDetailOne;
    @BindView(R.id.tv_detail_two)
    TextView tvDetailTwo;
    @BindView(R.id.position_container)
    ConstraintLayout positionContainer;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.title)
    RelativeLayout title;
    @BindView(R.id.iv1)
    ImageView iv1;
    @BindView(R.id.iv2)
    ImageView iv2;
    @BindView(R.id.tv1)
    TextView tv1;
    @BindView(R.id.btn_confirm)
    TextView btnConfirm;
    @BindView(R.id.tv_detail_one_title)
    TextView tvDetailOneTitle;
    @BindView(R.id.tv_remain_time_title)
    TextView tvRemainTimeTitle;
    @BindView(R.id.tv_detail_two_title)
    TextView tvDetailTwoTitle;
    @BindView(R.id.pay_title)
    RelativeLayout payTitle;
    @BindView(R.id.radio_group)
    RadioGroup radio_group;
    @BindView(R.id.tv_alipay)
    TextView tvAlipay;

    private CountDownTimer timer;
    private String hospitalName, receiverId = "", hospitalPhone, receiverName, receiverAddress, receiverPhone, prescriptionAmount;
    private IWXAPI api;
    private Boolean isChooseAddress = true;//是否可以选择地址
    MedicineListResponse.MedicineOrder order;
    List<PrescriptionResponse.Prescription> list = new ArrayList<>();
    MedicineAdapter adapter;
    AddressResponse address;
    String orderId;
    private String cardType;

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_medicine_detail;
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void initViews() {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        adapter = new MedicineAdapter(this, list);
        recyclerView.setAdapter(adapter);
        radio_group.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.btn_express:
//                    btnConfirm.setText("支付");
                    if (address != null) {
                        tv_addr.setVisibility(View.VISIBLE);
                        tv_phone.setVisibility(View.VISIBLE);
                        tv_phone.setText(receiverPhone);
                        tv_name.setText(receiverName);
                        tv_addr.setText(receiverAddress);
                    } else {
                        tv_phone.setText("");
                        tv_name.setText("");
                        tv_addr.setText("");
                    }
                    isChooseAddress = true;
                    ToastUtil.showToastCenter(mContext, "配送邮费将在收货时到付");
                    break;
                case R.id.btn_store_self://药店自取
//                    btnConfirm.setText("下单");
                    tv_addr.setVisibility(View.VISIBLE);
                    tv_phone.setVisibility(View.INVISIBLE);
                    tv_name.setText("药店");
                    tv_addr.setText("温州市鹿城区环城东路115号101室");
                    isChooseAddress = false;
                    break;
                case R.id.btn_hospital_self://医院自取
//                    btnConfirm.setText("下单");
                    tv_phone.setVisibility(View.INVISIBLE);
                    tv_addr.setVisibility(View.VISIBLE);
                    tv_addr.setText(hospitalPhone);
                    tv_name.setText(hospitalName);
                    isChooseAddress = false;
                    break;
                default:
                    break;
            }
        });
    }

    @Override
    protected void initData() {
        EventBus.getDefault().register(this);
        order = (MedicineListResponse.MedicineOrder) getIntent().getSerializableExtra("obj");
        //从聊天页面过来才带过来orderId
        orderId = getIntent().getStringExtra("orderId");
        if (order != null) {
            getMedicineOrderDetail(order.orderId);
            if (order.orderStatus == 401) {//待支付
                delivery_container.setVisibility(View.VISIBLE);
                express_container.setVisibility(View.GONE);
                pay_container.setVisibility(View.VISIBLE);
            } else {
                delivery_container.setVisibility(View.GONE);
                express_container.setVisibility(View.VISIBLE);
                pay_container.setVisibility(View.GONE);
            }
        } else {
            getMedicineOrderDetail(orderId);
            delivery_container.setVisibility(View.VISIBLE);
            express_container.setVisibility(View.GONE);
            pay_container.setVisibility(View.VISIBLE);
        }
    }

    private void getAlipaySwitch() {
        RestProxy.getInstance().getAlipaySwitch(new BaseObserver<SwitchResponse>() {
            @Override
            public void onSuccess(SwitchResponse result) {
                if (result.isFlag() && ("2".equals(cardType) || "3".equals(cardType))) {
                    tvAlipay.setVisibility(View.VISIBLE);
                } else {
                    tvAlipay.setVisibility(View.GONE);
                }
            }
        });
    }

    private void getMedicineOrderDetail(String orderId) {
        showLoadingDialog(mContext);
        RestProxy.getInstance().getMedicineOrderDetail(orderId, new Observer<PrescriptionResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onNext(PrescriptionResponse prescriptionResponse) {
                dismissLoadingDialog();
                if ("2".equals(prescriptionResponse.receiveType)) {//药店自取
                    tv_addr.setVisibility(View.VISIBLE);
                    tv_phone.setVisibility(View.INVISIBLE);
                    tv_name.setText("药店");
                    tv_addr.setText("温州市鹿城区环城东路115号101室");
                } else if ("3".equals(prescriptionResponse.receiveType)) {//医院自取
                    tv_phone.setVisibility(View.INVISIBLE);
                    tv_addr.setVisibility(View.VISIBLE);
                    tv_addr.setText(hospitalPhone);
                    tv_name.setText(hospitalName);
                } else {
                    receiverName = prescriptionResponse.receiverName;
                    receiverAddress = prescriptionResponse.receiverAddress;
                    receiverPhone = prescriptionResponse.receiverPhone;
                    receiverId = prescriptionResponse.receiverId;
                    if (!UtilString.isEmpty(prescriptionResponse.receiverName)) {
                        tv_name.setText(prescriptionResponse.receiverName);
                    }
                    if (!UtilString.isEmpty(prescriptionResponse.receiverAddress)) {
                        tv_addr.setText(prescriptionResponse.receiverAddress);
                    }
                    if (!UtilString.isEmpty(prescriptionResponse.receiverPhone)) {
                        tv_phone.setText(prescriptionResponse.receiverPhone);
                    }
                }
                tv_notice.setText("用药嘱托:" + prescriptionResponse.remark);
                tv_hospital.setText(prescriptionResponse.hospitalName);
                tv_doctor.setText("医师：" + prescriptionResponse.doctorName);
                tvMedicineDoctor.setText("药师：" + prescriptionResponse.prescriptionDocName);
                tv_time.setText(prescriptionResponse.preTime);
                tv_phone_num.setText(prescriptionResponse.hospitalPhone);
                prescriptionAmount = prescriptionResponse.prescriptionAmount;
                tv_price.setText("¥" + prescriptionResponse.prescriptionAmount);
                tv_price2.setText("合计：¥" + prescriptionResponse.prescriptionAmount);
                hospitalName = prescriptionResponse.hospitalName;
                hospitalPhone = prescriptionResponse.hospitalPhone;
                tv_patient_no.setText("病历号:" + prescriptionResponse.medicalId);
                tv_express_status.setText(getStatus(prescriptionResponse.orderStatus));
                tv_patient_name.setText(prescriptionResponse.patientName);
                tv_patient_detail.setText(prescriptionResponse.patientSex + "  " + prescriptionResponse.patientAge);
                tv_diagnose.setText("主诊诊断:" + prescriptionResponse.preAppend + "-" + prescriptionResponse.icd + "-" + prescriptionResponse.tailAppend);
                tv_advice.setText("医生建议:" + prescriptionResponse.diagnoseAdvice);
                //tv_remain_time.setText( "请在" + Integer.parseInt( prescriptionResponse.data.remainPayTime ) / 60 + "分钟之内完成支付" );
                final int parseInt = Integer.parseInt(prescriptionResponse.remainPayTime);
                timer = new CountDownTimer(parseInt * 1000, 1000) {
                    @Override
                    public void onTick(long millisUntilFinished) {

                        String text = millisUntilFinished / 60000 / 60 + "时" + millisUntilFinished / 60000 % 60 + "分" + (millisUntilFinished / 1000) % 60 + "秒";
                        tv_remain_time.setText(text);
                        tvRemainTimeTitle.setText(text);
                    }

                    @Override
                    public void onFinish() {
                        //倒计时为0时执行此方法
                        tv_remain_time.setText("已超时");
                        tvRemainTimeTitle.setText("已超时");
                        timer.cancel();
                        tvDetailOne.setVisibility(View.GONE);
                        tvDetailTwo.setVisibility(View.GONE);
                        tvDetailOneTitle.setVisibility(View.GONE);
                        tvDetailTwoTitle.setVisibility(View.GONE);
                        btnConfirm.setVisibility(View.GONE);


                    }
                };
                timer.start();
                list.clear();
                list.addAll(prescriptionResponse.westernNameDtoList);
                adapter.notifyDataSetChanged();
                if (prescriptionResponse.orderStatus != 401) {
                    //不是待支付
                    positionContainer.setEnabled(false);
                }
                btn_store_self.setVisibility(View.GONE);

                cardType = prescriptionResponse.cardType;
//                getAlipaySwitch();

            }

            @Override
            public void onError(Throwable e) {
                dismissLoadingDialog();
                ToastUtil.onError(mContext, e);
            }

            @Override
            public void onComplete() {

            }
        });
    }

    @OnClick(R.id.position_container)
    void position_container() {
        if (isChooseAddress) {
            Intent intent = new Intent(this, MyAddressActivity.class);
            intent.putExtra("isFromMine", false);
            startActivityForResult(intent, 1);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 1) {
            address = (AddressResponse) data.getSerializableExtra("obj");
            assert address != null;
            receiverId = address.id;
            receiverAddress = address.addr;
            receiverName = address.consigneeName;
            receiverPhone = address.consigneePhone;
            tv_name.setText(address.consigneeName);
            tv_addr.setText(address.addr);
            tv_phone.setText(address.consigneePhone);
        }
    }

    private String getStatus(int status) {
        switch (status) {
            case 401:
                return "待支付";
            case 402:
                return "未发货";
            case 403:
                return "已发货";
            case 404:
                return "已收货";
            case 405:
                return "待领取";
            default:
                return "";
        }
    }


    private void createWXOrder(String orderId) {
        String getType = "";
        if (btn_express.isChecked()) {
            if (UtilString.isEmpty(receiverId)) {
                ToastUtil.showToastCenter(mContext, "请选择收货地址");
                return;
            }
        } else if (btn_store_self.isChecked()) {
            receiverId = "";
            getType = "2";
        } else if (btn_hospital_self.isChecked()) {
            receiverId = "";
            getType = "3";
        } else {
            ToastUtil.showToastCenter(this, "请先选择收货方式");
            return;
        }
        showLoadingDialog(mContext);
        RestProxy.getInstance().createOrder(orderId, prescriptionAmount, receiverId, getType, new BaseObserver<PayResponse>() {
            @Override
            public void onSuccess(PayResponse payResponse) {
                dismissLoadingDialog();
                switch (payResponse.getType) {
                    case 1:
                        BaseApplication.diagnoseType = -1;
                        BaseApplication.currentWXId = payResponse.appid;
                        api = WXAPIFactory.createWXAPI(mContext, payResponse.appid);
                        PayReq request = new PayReq();
                        request.appId = payResponse.appid;
                        request.partnerId = payResponse.partnerid;
                        request.prepayId = payResponse.prepayid;
                        request.packageValue = "Sign=WXPay";
                        request.nonceStr = payResponse.noncestr;
                        request.timeStamp = payResponse.timestamp;
                        request.sign = payResponse.sign;
                        api.sendReq(request);
                        break;
                    case 2:
                        ToastUtil.showToast(mContext, "请到药店自取");
                        break;
                    case 3:
                        ToastUtil.showToast(mContext, "请到医院自取");
                        break;
                    case 4:
                        ToastUtil.showToast(mContext, "医保已全额报销");
                        break;
                    default:
                        break;
                }
                setResult(RESULT_OK);
                finish();
            }

            @Override
            public void onError(Throwable e) {
                dismissLoadingDialog();
                ToastUtil.onError(mContext, e);
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
        EventBus.getDefault().unregister(this);
    }


    @OnClick({R.id.btn_confirm, R.id.tv_alipay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_confirm:
                if (order != null) {
                    BaseApplication.currentOrderId = order.orderId;
                    createWXOrder(order.orderId);
                } else {
                    BaseApplication.currentOrderId = orderId;
                    createWXOrder(orderId);
                }
                break;
            case R.id.tv_alipay:
                if (checkAliPayInstalled(mContext)) {
                    if (btn_express.isChecked()) {
                        if (UtilString.isEmpty(receiverId)) {
                            ToastUtil.showToastCenter(mContext, "请选择收货地址");
                            return;
                        }
                    }
                    Intent intent = new Intent(mContext, AtyAliPayResult.class);
                    if (order != null) {
                        intent.putExtra("orderId", order.orderId);
                    } else {
                        intent.putExtra("orderId", orderId);
                    }
                    intent.putExtra("receiveId", receiverId);
                    intent.putExtra("getType", btn_express.isChecked() ? "1" : "3");
                    startActivity(intent);
                } else {
                    ALiPayDialog aLiPayDialog = ALiPayDialog.newInstance();
                    aLiPayDialog.show(getSupportFragmentManager(), "aLiPayDialog");
                }
                break;
            default:
                break;
        }
    }

    public static boolean checkAliPayInstalled(Context context) {

        Uri uri = Uri.parse("alipays://platformapi/startApp");
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        ComponentName componentName = intent.resolveActivity(context.getPackageManager());
        return componentName != null;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAlipaySuccessEvent(AlipaySuccessEvent event) {
        finish();
    }
}
